package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.IPublishService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
public class PublishServiceImpl implements IPublishService {


    @Autowired(required = false)
    private Configuration cfg;

    @Autowired(required = false)
    private MinIOService minIOService;

    @Autowired(required = false)
    private IApArticleService articleService;

    @Async
    @Override
    public void createHtml(ApArticle article, String content) {
        // 添加freemarker依赖
        // 配置默认后缀
        // 获取 Configuration 实例,在SpringBoot 应用中添加了spring-boot-starter-freemarker 会自动配置这个实例,只需要注入
        // 通过实例获取模板文件
        try {
            System.out.println(Thread.currentThread().getName() + "开始执行静态页面生成...");
            Template template = cfg.getTemplate("article.ftl");
            // 读取数据模型
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            // 合并模板和模型
            StringWriter ws = new StringWriter();
            template.process(map, ws);
            // 生成html文件
            // 将html文件上传到minio
            InputStream is = new ByteArrayInputStream(ws.toString().getBytes());
            String url = minIOService.upload(article.getId() + ".html", is, "text/html");
            // 将上传后的地址更新回文章表的静态页面字段
            article.setStaticUrl(url);
            articleService.updateById(article);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
